<?php
// Fatal Error Handler
// Registering shutdown function
register_shutdown_function("fatal_handler");
function fatal_handler()
{
  // Getting last error
    global $CONFIG;
    $errno = error_get_last();
    if ($errno['type'] === E_ERROR) {
        $body = "<table><thead bgcolor='#c8c8c8'><th>Item</th><th>Description</th></thead><tbody>";
        $body .= "<tr valign='top'><td><b>Error</b></td><td><pre>{$errno['message']}</pre></td></tr>";
        $body .= "<tr valign='top'><td><b>Errno</b></td><td><pre>{$errno['type']}</pre></td></tr>";
        $body .= "<tr valign='top'><td><b>File</b></td><td>{$errno['file']}</td></tr>";
        $body .= "<tr valign='top'><td><b>Line</b></td><td>{$errno['line']}</td></tr>";
        $body .= '</tbody></table>';
        $body .= '<br />$_POST<br/>';
        $body .= print_r($_POST, true);
        $body .= '<br />$_SERVER<br/>';
        $body .= print_r($_SERVER, true);
        if ($CONFIG->attributes()->staging == 'true' || $_SERVER['REMOTE_ADDR'] == '192.168.10.10') {
            die($body);
        }
        $subject = "Fatal error";
        $to = "liu.chang@chinaott.net";
        $from = (string) $CONFIG->company->name;
        $from = empty($from)?"website":$from;
        $fromEmail = 'noreply@' . str_replace("www.", "", $HTTP_HOST);
        /* To send HTML mail, you can set the Content-type header. */
        $headers  = "MIME-Version: 1.0\r\n";
        $headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
        $headers .= "X-Priority: 3\r\n";
        $headers .= "X-Mailer: PHP". phpversion() ."\r\n";
        /* additional headers */
        $headers .= "Reply-To: ". $from . " <".$fromEmail.">\r\n";
        $headers .= "Return-Path: ". $from . " <".$fromEmail.">\r\n";
        $headers .= "From: ". $from . " <".$fromEmail.">\r\n";
        try {
            // $filename = $_SERVER['DOCUMENT_ROOT'].'fatalerror'. date("Y-m-d-H") .'.txt';
            // if (!file_exists($filename)) {
            //     file_put_contents($filename, $body);
            //     mail($to, $subject, $body, $headers, "-f $fromEmail");
            // }
        } catch (Exception $e) {
        }
    
        $_SESSION['error'] = '网站运行中出错，请您再试一次，如果还出现此问题，请联系我们。';
        header('location: /503.html');
        die('503 服务暂时不可用');
    }
}

set_include_path($_SERVER['DOCUMENT_ROOT']);  //SET THE INCLUDE PATH TO DOCUMENT ROOT SO THAT ALL INCLUDES ARE DONE RELATIVE TO WEB FOLDER
ini_set('display_errors', 0);
ini_set('error_reporting', 0);
ini_set('date.timezone', 'Asia/Shanghai');
error_reporting(0);

$_CONF_FILE = "/config/config.xml.php";
$GLOBALS['CONFIG'] = loadConfig($_CONF_FILE);
$GLOBALS['SITE'] = "";
$GLOBALS['HTTP_HOST'] = (!empty($_SERVER['SERVER_NAME'])?$_SERVER['SERVER_NAME']:"");

include_once 'database/pdo-db-manager.php';
include_once 'database/table-class.php';
include_once 'database/utilities.php';
include_once 'smarty/Smarty.class.php';

ini_set('session.gc_maxlifetime', 7200);
session_set_cookie_params(7200);
session_start();

$_REQUEST = htmlclean($_REQUEST);
$_POST = htmlclean($_POST);
$_GET = htmlclean($_GET);

$_SECURE_COOKIE = false;
if ($_SERVER['SERVER_PORT'] == 443 || !empty($_SERVER['HTTPS'])) {
    $_SECURE_COOKIE = true; /*IF HTTPs TURN THIS ON */
}
$currentCookieParams = session_get_cookie_params();
$sidvalue = session_id();
setcookie(
    'PHPSESSID', //name
    $sidvalue, //value
    0, //expires at end of session
    $currentCookieParams['path'], //path
    $currentCookieParams['domain'], //domain
    $_SECURE_COOKIE, //secure
    true  //httponly: Only accessible via http. Not accessible to javascript
);

$_PUBLISHED = 1; // ASSIGN PUBLISHED 1 THIS IS TO MAKE SURE ALL PAGES WHICH ARE LOADED ARE PUBLISHED
// ASSIGN DRAFT VARIABLE IF THE URL CONTAINS "DRAFT". ALSO SET CONFIG TO STAGING = TRUE TO PREVENT GOOGLE INDEX.
$uri_prefix_draft = "/(^|\s)(draft\/)/";
if (preg_match($uri_prefix_draft, $_REQUEST['arg1'])) {
    $_REQUEST['arg1'] = preg_replace($uri_prefix_draft, "", $_REQUEST['arg1']);
    $_DRAFT = true;
    $_PUBLISHED = 0; // UPDATE PUBLISHED TO 0 TO LOAD THE DRAFT VERSIONS
}

//$SMARTY;
$_match_subsite = false;
foreach ($CONFIG->subsite as $sub) {
    $needle = str_replace("/", "\/", $sub->url);
    if (preg_match("/^{$needle}/", $_REQUEST["arg1"])) {
        $GLOBALS['SITE'] = $sub->url;
        $GLOBALS['CONFIG'] = LOADCONFIG($sub->config);
        $_REQUEST["arg1"] = trim(str_replace("{$needle}", "", $_REQUEST["arg1"]), "/");
        //SET COOKIE FOR SUBSITE
        $currentCookieParams = session_get_cookie_params();
        setcookie(
            'sub_site', //name
            $needle, //value
            time()+(60*60*24*30), //expires at end of session
            $currentCookieParams['path'], //path
            $currentCookieParams['domain'], //domain
            $_SECURE_COOKIE, //secure
            true  //httponly: Only accessible via http. Not accessible to javascript
        );
        $_match_subsite = true;
    }
}
if (!empty($_COOKIE["sub_site"]) && !$_match_subsite) {
    $lowercase_file_url = strtolower(isset($_SERVER['HTTPS'])?"https://":"http://" . $GLOBALS['HTTP_HOST'] .'/'.$_COOKIE["sub_site"] . $_SERVER['REQUEST_URI']);
    header("Location: $lowercase_file_url");
    exit();
}

include_once 'database/listing-class.php';
include_once 'database/product-class.php';
include_once 'database/classterm-class.php';
include_once 'database/user-class.php';
include_once 'database/member-class.php';
include_once 'database/region-class.php';
include_once 'database/cart-class.php';
include_once 'database/enrolment-class.php';
include_once 'database/CommBank-class.php';
include_once 'database/shipping-class.php';
//include_once 'database/queue-class.php';

include_once 'includes/functions/functions-search.php';
include_once 'includes/processes/processes.php';
include_once 'includes/1card1/OpenApiClient.php';

if (! empty($CONFIG->database->host) && ! empty($CONFIG->database->user) && ! empty($CONFIG->database->password) && ! empty($CONFIG->database->dbname)) {
    $GLOBALS['DBobject'] = new DBmanager();
}

if (! empty($CONFIG->socialwall)) {
    $GLOBALS['SOCIAL'] = INITSOCIALWALL($CONFIG);
}

if (!empty($CONFIG->ecarde->openid) && !empty($CONFIG->ecarde->secret)) {
    $GLOBALS['Cardclient'] = new OpenApiClient($CONFIG->ecarde->openid, $CONFIG->ecarde->secret);
}

$GLOBALS['SMARTY'] = INITSMARTY($CONFIG);

$staging = (string)$CONFIG->attributes()->staging;
if ($staging === "true" || $_PUBLISHED == 0) {
    $SMARTY->assign("staging", true);
    $GLOBALS['GA_ID'] = null;
} else {
    $SMARTY->assign("staging", false);
    $ga_id = (string) $CONFIG->google_analytics->id;
    $SMARTY->assign("ga_id", $ga_id);
    $GLOBALS['GA_ID'] = $ga_id;
    $ga_old_id = (string) $CONFIG->google_analytics->old_id;
    $SMARTY->assign("ga_old_id", $ga_old_id);
}

$curSym = (string) $CONFIG->currency->symbol;
$GLOBALS['CURRENCY_SYMBOL'] = empty($curSym)?'$':$curSym;
$SMARTY->assign("CURRENCY_SYMBOL", $GLOBALS['CURRENCY_SYMBOL']);
$curCode = (string) $CONFIG->currency->code;
$GLOBALS['CURRENCY_CODE'] = empty($curCode)?'AUD':$curCode;
$SMARTY->assign("CURRENCY_CODE", $GLOBALS['CURRENCY_CODE']);
$taxCode = (string) $CONFIG->tax->code;
$GLOBALS['TAX_CODE'] = empty($taxCode)?'GST':$taxCode;
$SMARTY->assign("TAX_CODE", $GLOBALS['TAX_CODE']);
$taxRate = floatval($CONFIG->tax->rate);
$GLOBALS['TAX_RATE'] = empty($taxRate)?0:$taxRate;
$SMARTY->assign("TAX_RATE", $GLOBALS['TAX_RATE']);

$GLOBALS['PHONE'] = (string) $CONFIG->company->phone;
$SMARTY->assign("PHONE", $GLOBALS['PHONE']);

$socialLinks = array();
foreach ($CONFIG->social_links as $key => $val) {
    $socialLinks["{$key}"] = (string) $val;
}
$SMARTY->assign("social_links", $socialLinks);

if (isMobile()) {
    $SMARTY->assign("mobile", true);
}
$config_arr = xmlToArrayElement($CONFIG);
//var_dump($config_arr);exit;
$SMARTY->assign("config", $config_arr);


function xmlToArrayElement($xmlobject)
{
    $data = array();
    foreach ((array) $xmlobject as $key => $value) {
        $data[$key] = !is_string($value) ? xmlToArrayElement($value) : $value;
    }
    return $data;
}

//SECTION HOLDS THE INIT FUNCTIONS
function loadConfig($_CONF_FILE)
{
    if (is_file($_SERVER['DOCUMENT_ROOT'] . $_CONF_FILE)) {
        $xml = file_get_contents($_SERVER['DOCUMENT_ROOT'] . $_CONF_FILE);
        $CONFIG = simplexml_load_string($xml);
        if ($CONFIG !== false) {
            $debug = (string)$CONFIG->attributes()->debug;
            if ($debug == 'true') {
                ini_set('display_errors', 1);
                ini_set('error_reporting', E_ALL ^ E_NOTICE ^ E_WARNING ^ E_STRICT);
            } //ENABLE ERRORS IF DEBUG ON
            return $CONFIG;
        }
    }
    ini_set('display_errors', 1);
    echo "configuration file not loaded";
    die(); //CONFIG DOES NOT EXIST. DIE AND TELL USER
}

function INITSOCIALWALL($CONFIG)
{
    include_once 'includes/social/youtube.class.php';
    include_once 'includes/social/instagram.class.php';
    include_once 'includes/social/twitter.class.php';
    include_once 'includes/social/facebook.php';
    include_once 'includes/social/socialwall.class.php';
  
    $tag = $CONFIG->socialwall->tag;
    $table = $CONFIG->socialwall->table;
    $ads = $CONFIG->socialwall->ads == true?true:false;
    $instagram = $CONFIG->socialwall->attributes()->instagram == "true"?true:false;
    $facebook = $CONFIG->socialwall->attributes()->facebook == "true"?true:false;
    $youtube = $CONFIG->socialwall->attributes()->youtube == "true"?true:false;
    $twitter = $CONFIG->socialwall->attributes()->twitter == "true"?true:false;
    return new SocialWall($tag, $table, $ads, $instagram, $facebook, $youtube, $twitter);
}

function INITSMARTY($CONFIG)
{
  // Create Smarty object and set
  // paths within object
    $SMARTY = new Smarty();
    $SMARTY->template_dir = $_SERVER['DOCUMENT_ROOT'] . "/" . $CONFIG->smartytemplate_config->templates; // name of directory for templates
    $SMARTY->compile_dir = $_SERVER['DOCUMENT_ROOT'] . "/" . $CONFIG->smartytemplate_config->templates_c; // name of directory for compiled templates
    $SMARTY->plugins_dir = array(
      $_SERVER['DOCUMENT_ROOT'] . "/" . $CONFIG->smartytemplate_config->plugins,
      $_SERVER['DOCUMENT_ROOT'] . "/smarty/plugins"
    ); // plugin directories
    $SMARTY->cache_dir = $_SERVER['DOCUMENT_ROOT'] . "/" . $CONFIG->smartytemplate_config->cache; // name of directory for cache
    $debug = (string)$CONFIG->attributes()->debug;
    if ($debug == 'true') {
        $SMARTY->debugging = true;
        $SMARTY->force_compile = true;
        $SMARTY->caching = false;
    } else {
        $SMARTY->debugging = false;
        $SMARTY->force_compile = false;
        $SMARTY->caching = false;
    }
    return $SMARTY;
}
